package com.geeksx.trainer.controller;

import com.geeksx.trainer.common.api.Result;
import com.geeksx.trainer.common.utils.JwtUtil;
import com.geeksx.trainer.entity.User;
import com.geeksx.trainer.entity.request.RegisterRequest;
import com.geeksx.trainer.entity.request.UserProfileRequest;
import com.geeksx.trainer.entity.vo.UserVO;
import com.geeksx.trainer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Copyright (C), 2025, 北京同创永益科技发展有限公司
 *
 * @Classname UserController
 * @Description TODO
 * @Date 2025/8/26 14:55
 * @Created by zhengkaixuan
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Value("${file.upload-avatar-dir}")
    private String uploadAvatarDir;
    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     *  注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest request) {
        if (userService.register(request)){
            return Result.success("注册成功");
        }
        return Result.failure("注册失败");
    }

    /**
     * 登录
     * @param loginUser
     * @return
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody User loginUser) {
        log.info("loginUser:{}", loginUser);
        Authentication authenticate = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword()));
        UserDetails userDetails = (UserDetails)authenticate.getPrincipal();
        String token = jwtUtil.generateToken(userDetails.getUsername());
        UserVO userVO = userService.getByLoginName(loginUser.getUsername());
        userVO.setToken(token);
        return Result.success(userVO);
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        return Result.success(userService.getById(id));
    }

    /**
     * 修改用户信息
     * @param request
     * @return
     */
    @PutMapping("/profile")
    public Result<?> updateProfile(@RequestBody UserProfileRequest request) {
        userService.updateProfile(request);
        return Result.success();
    }

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/uploadAvatar")
    public Result<?> uploadAvatar(@RequestParam("file") MultipartFile file,@RequestParam Long userId) {
        if (file.isEmpty()){
            return Result.failure("上传文件不能为空");
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();


        // 保存文件
        String filePath = uploadAvatarDir + originalFilename;
        log.info("uploadAvatar filePath:{}", filePath);
        try {
            file.transferTo(new File(filePath));
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return Result.failure("上传文件失败");
        }

        userService.updateUserAvatar(userId,filePath);

        return Result.success();
    }

}
